//
//  CommonUtil.m
//  homeland
//
//  Created by gzbugu on 14-7-29.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//  公共方法实现类
//

#import "CommonUtil.h"
#import<SystemConfiguration/SCNetworkReachability.h>

@implementation CommonUtil

/**处理null字符串对象*/
+ (NSString *)dealNullObject:(NSString*)objStr{
    if (objStr == nil || objStr == NULL) {
        return @"";
    }else
        if ([objStr isKindOfClass:[NSNull class]]) {
            return @"";
        }else
            if((NSNull *)objStr == [NSNull null] || !objStr){
                return @"";
            }else{
                return [NSString stringWithFormat:@"%@",objStr];
            }
}
/**格式化时间字符串
 *@param dateStr 时间字符串
 *@param style 格式化样式
 */
+ (NSString *)formatDateStr:(NSString*)dateStr style:(NSString*)style{
    NSError* error = nil;
    if (dateStr == nil || dateStr == NULL || (NSNull *)dateStr == [NSNull null]  || !dateStr) {
        return @"";
    }else{
        dateStr =[dateStr stringByReplacingOccurrencesOfString:@".0" withString:@""];
        NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
        [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate* inputDate = [inputFormatter dateFromString:dateStr];
    
        NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
        [outputFormatter setLocale:[NSLocale currentLocale]];
        [outputFormatter setDateFormat:style];
        NSString *str = [outputFormatter stringFromDate:inputDate];
        if (error != nil) return nil;
        return str;
    }
}


#pragma mark - Draw Line
+ (UIImage *)drawLineWithColor:(UIColor *)color width:(CGFloat)width startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint theView:(UIView *)theView{
    UIImage *image = nil;
    
    //创建一个基于位图的上下文
    UIGraphicsBeginImageContext(theView.frame.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetLineWidth(context, width);
    CGContextSetStrokeColorWithColor(context, [color CGColor]);
    
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
    
    CGContextStrokePath(context);
    
    image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage *)getLocalDot9Image:(NSString *)imageName{
    double version = [[UIDevice currentDevice].systemVersion doubleValue];//判定系统版本。
    UIImage *image;
    if (version > 5.0) {
        image = [[UIImage imageNamed:imageName] resizableImageWithCapInsets:UIEdgeInsetsMake(10,10,10,10)];
    }else{
        image = [[UIImage imageNamed:imageName] stretchableImageWithLeftCapWidth:10 topCapHeight:10];
    }
    return image;
}

+ (BOOL)connectedToNetwork{
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_storage zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags){
        return NO;
    }
    //根据获得的连接标志进行判断
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable&&!needsConnection) ? YES : NO;
}


//转换数值型字符串为纯字符串
+(NSString *)toPureString:(NSString*)string{
    NSString *newString;
    //double字符串
    if ([string isPureDouble:string]) {
        double doubleString = [string doubleValue];
        newString = [NSString stringWithFormat:@"%f",doubleString];
    }else
        //int字符串
        if ([string isPureInt:string]) {
            int intString = [string intValue];
            newString = [NSString stringWithFormat:@"%d",intString];
        }else
            //Integer字符串
            if ([string isPureInteger:string]) {
                NSInteger integerString = [string integerValue];
                newString = [NSString stringWithFormat:@"%d",integerString];
            }else
                //float字符串
                if ([string isPureFloat:string]) {
                    float floatString = [string floatValue];
                    newString = [NSString stringWithFormat:@"%f",floatString];
                }else
                    //long字符串
                    if ([string isPureLong:string]) {
                        long long longString = [string longLongValue];
                        newString = [NSString stringWithFormat:@"%lld",longString];
                    }else
                        //decimal字符串
                        if ([string isPureDecimal:string]) {
                            double decimalString = [string doubleValue];
                            newString = [NSString stringWithFormat:@"%f",decimalString];
                        }else{
                            newString = string;
                        }
    return newString;
}

/**NSDictionary 转换为 NSString
 *@param dic
 */
+ (NSString *) dicToString:(NSDictionary*)nsd{
    NSError* error = nil;
    //转换为json格式字符串
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:nsd options:(NSJSONWritingOptions)0 error:nil];
    NSString *jsonStr = [[NSString alloc] initWithBytes:[jsonData bytes] length:jsonData.length encoding:NSUTF8StringEncoding];
    if (error != nil) return nil;
    return jsonStr;
}

/** json格式NSString转换为NSDictionary
 *@param jsonStr
 */
+ (NSDictionary *)stringToDic:(NSString *)jsonStr{
    NSError* error = nil;
    NSData* data =[jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    if (error != nil) return nil;
    return dic;
}

/**
 *四舍五入
 *@param number 需要处理的数字
 *@param scale 保留小数点第几位，
 *
 */
+ (NSString *)roundUp:(float)number afterScale:(int)scale{
    NSError* error = nil;
     NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundUp scale:scale raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
     NSDecimalNumber *ouncesDecimal;
     NSDecimalNumber *roundedOunces;
     ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:number];
     roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    if (error != nil) return nil;
    return [NSString stringWithFormat:@"%@",roundedOunces];
}

/**
 *十六进制颜色转UIColor
 *@param str @"#0099cc"格式字符串
 */
+ (UIColor *) stringToColor:(NSString *)str{
    if (!str || [str isEqualToString:@""]) {
        return nil;
    }
    unsigned red,green,blue;
    NSRange range;
    range.length = 2;
    range.location = 1;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&red];
    range.location = 3;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&green];
    range.location = 5;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&blue];
    UIColor *color= [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1];
    return color;
}
+(UIButton*)createBottonBtn:(NSString*)imageName  btnName:(NSString*)btnName selector:(SEL)selectorName delegate:(id)delegate{
    int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭
    UIButton *postBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,460 - height,320 , 44)];
    [postBtn setBackgroundImage:[UIImage imageNamed:imageName] forState:0];
    [postBtn setTitle:btnName forState:0];
    
    [postBtn addTarget:delegate action:selectorName forControlEvents:UIControlEventTouchUpInside];
    return postBtn;
}
+ (NSString *)formatDateStrStyle:(NSString*)style{
    NSDate * date = [NSDate date];
    NSTimeInterval sec = [date timeIntervalSinceNow];
    NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
    
    //设置时间输出格式：
    NSDateFormatter * df = [[NSDateFormatter alloc] init ];
    [df setDateFormat:style];
    NSString * na = [df stringFromDate:currentDate];
    return na;
}
@end
